import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:signage/app/modules/splash/controllers/splash_controller.dart';
import 'package:signage/app/services/bluetooth_service.dart';
import 'package:signage/l10n/l10n.dart';
import 'app/routes/app_pages.dart';
import 'app/utils/config.dart';
import 'package:get_storage/get_storage.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() async {
  Get.put(BluetoothManager());
  final prefs = await SharedPreferences.getInstance();
  final savedLanguage = prefs.getString('app_language');
  final Locale? initialLocale = savedLanguage != null && savedLanguage.isNotEmpty 
      ? Locale(savedLanguage) 
      : null;
      
  Config.init(() => runApp(
    MyApp(initialLocale: initialLocale),
  ));
}

class MyApp extends StatelessWidget {
  final Locale? initialLocale;
  MyApp({super.key, this.initialLocale});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return GetBuilder<SplashController>(
      init: SplashController(),
      builder: (ctrl) => ScreenUtilInit(
        designSize: const Size(375, 812), // 设计稿尺寸
        minTextAdapt: true,
        splitScreenMode: true,
        builder: (context, child) {
          return GetMaterialApp(
            localizationsDelegates: const [
              AppLocalizations.delegate,
              GlobalMaterialLocalizations.delegate,
              GlobalWidgetsLocalizations.delegate,
              GlobalCupertinoLocalizations.delegate,
            ],
            supportedLocales: const [
              Locale('en'),
              Locale('zh'),
            ],
            locale: initialLocale ?? Get.deviceLocale,
            builder: (context, child) {
              return FlutterEasyLoading(
                child: child,
              );
            },
            title: "Application",
            theme: ThemeData(
              primaryColor: const Color(0xFFFCCF01),
              colorScheme: ColorScheme.fromSeed(
                seedColor: const Color(0xFFFCCF01),
                primary: const Color(0xFFFCCF01),
              ),
              bottomNavigationBarTheme: const BottomNavigationBarThemeData(
                selectedItemColor: Color(0xFFFCCF01),
                unselectedItemColor: Colors.grey,
              ),
              elevatedButtonTheme: ElevatedButtonThemeData(
                style: ElevatedButton.styleFrom(
                  backgroundColor: Color(0xFFFCCF01),
                ),
              ),
            ),
            initialRoute: AppPages.INITIAL,
            getPages: AppPages.routes,
            fallbackLocale: const Locale('en'),
          );
        },
      ),
    );
  }
}

class GlobalController extends GetxController {}
